
#include "MainImg.h"

MainImg::MainImg(QWidget *parent) :
	QWidget(parent)
{

}

MainImg::~MainImg()
{

}

void MainImg::onReceiveDepthFrame(QByteArray depthData)
{
	char *pData = depthData.data();

	int depthWidth = *(int *)(pData + DATA_OFFSET + 1);
	int depthHeight = *(int *)(pData + DATA_OFFSET + 5);

	int depthSize = *(qint64 *)(pData + DATA_OFFSET + 17);

	unsigned short *rawData = (unsigned short *)(pData + DATA_OFFSET + 25);

	img = QImage(depthWidth, depthHeight, QImage::Format_RGB888);

	if (isVisible())
	{
		unsigned short maxDepth = 0;
		int size = qMin(depthWidth * depthHeight, depthSize);

		for (int i = 0; i < size; i++)
		{
			unsigned short depth = rawData[i];
			//depth = ((depth & 0x00FF) << 8) + ((depth & 0xFF00) >> 8);

			if (depth > maxDepth)
			{
				maxDepth = depth;
			}
		}

		for (int y = 0; y < depthHeight; y++)
		{
			uchar *line = img.scanLine(y);
			for (int x = 0; x < depthWidth; x++)
			{
				int index = y * depthWidth + x;
				if (index < depthSize)
				{
					unsigned short depth = rawData[index];

					//depth = ((depth & 0x00FF) << 8) + ((depth & 0xFF00) >> 8);

					int gray = static_cast<int>(depth * 255.0 / maxDepth);

					line[x * 3] = gray;     // R
					line[x * 3 + 1] = gray; // G
					line[x * 3 + 2] = gray; // B
				}
			}
		}

		update();
	}
}

void MainImg::paintEvent(QPaintEvent *event)
{
	QPainter painter(this);

	QRect rect(0, 0, width(), height());

	painter.drawImage(rect, img);
}

